Ext.define('YX.ZbusRpc', {
    extend: 'Ext.data.Connection',
    requires: ['Ext.data.Connection'],
    singleton: true,
    module: '',
    init: function (cfg) {
        if (cfg && cfg.host) {
            this.broker = new Broker(cfg.host);
        }
        if (cfg && cfg.topic) {
            this.topic = cfg.topic;
        }
    },
    /**
		 * 使用同Ext.Ajax 额外配置： options.module(后台服务名，字符串)
		 * options.showFail(操作失败是否显示错误对话框，默认:true
		 * options.showSuccess(操作成功是否显示成功对话框，默认:false)
		 */
    request: async function (options) {
        options = options || {};
        options.params = options.params||{};
        var me = this;
        Ext.apply(options.params,me.extraParams||{});
        options.scope = options.scope || window;
        options.module = options.module || options.url || me.module;
        options.showFail = options.showFail || true;
        options.showSuccess = options.showSuccess || false;

        if (Ext.isEmpty(me.broker) || Ext.isEmpty(me.topic)) {
            Ext.Error.raise("Broken is invalid.");
            return;
        }

        var parms = [];
        if (Ext.isArray(options.params)) {
            options.parms[0].requestToken = options.token || LoginInfo.TOKEN;
            parms = options.params;
        } else {
            options.params.requestToken = options.token || LoginInfo.TOKEN;
            parms.push(options.params)
        };
        
        // 表单提交
        var formDom = me.getForm(options);
        if(formDom){
        	//Ext.apply(parms[0],Ext.getCmp(options.form).getValues());
	        if (me.isFormUpload(options)) {
	                //Ext.apply(parms[0],await me.resolveFormRequest(options.form));
	                options.form.submit( {  
	                    waitTitle : '请稍后...',  
	                    waitMsg : '正在保存用户信息,请稍后...',  
	                    url : 'upload',  
	                    method : 'POST', 
						params: {
							module : options.module,
					        requestToken : LoginInfo.TOKEN
					    } ,
	                    success : function(form, action) {  
							if(options.success){
								Ext.callback(options.success, options.scope, [rsp, action]);
							}
							Ext.Msg.show({
	                            title: rsp.rspCode,
	                            msg: rsp.rspDesc,
	                            icon: Ext.Msg.INFO,
	                            buttons: Ext.Msg.OK
	                        });
							
							if(options.callback){
								Ext.callback(options.callback, options.scope, [rsp, action]);
							}
	                    },  
	                    failure : function(form, action) { 
							var rsp = action.result;
							if("SYS-0000" === rsp.rspCode){
								if(options.success){
									Ext.callback(options.success, options.scope, [action.result, action]);
									Ext.Msg.show({
			                            title: rsp.rspCode,
			                            msg: rsp.rspDesc,
			                            icon: Ext.Msg.INFO,
			                            buttons: Ext.Msg.OK
			                        });
								}
							}else{
								if(options.failure){
									Ext.callback(options.failure, options.scope, [action.result, action]);
								}
								Ext.Msg.show({
		                            title: rsp.rspCode,
		                            msg: rsp.rspDesc,
		                            icon: Ext.Msg.ERROR,
		                            buttons: Ext.Msg.OK
		                        });
							}
							if(options.callback){
								Ext.callback(options.callback, options.scope, [action.result, action]);
							}	
	                    }
	                }); 
					return;
	                //表单ajax提交
	                Ext.Ajax.request({
				    url: 'upload?module='+options.module,
				    jsonData:{
				    	requestToken : LoginInfo.TOKEN
				    },
				    form : options.form,
				    isUpload : options.isUpload,
				    success: function(rsp, opts) {
				    	if (options.showSuccess) {
	                        Ext.Msg.show({
	                            title: rsp.rspCode,
	                            msg: rsp.rspDesc,
	                            icon: Ext.Msg.INFO,
	                            buttons: Ext.Msg.OK,
	                            fn:function(){
	                            	if(Ext.isFunction(options.msgFn)){
	                            		 Ext.callback(options.msgFn, options.scope, [rsp, opts]);
	                            	}
	                            }
	                        });
	                    }
                    
				         Ext.callback(options.success, options.scope, [rsp, opts]);
				    },
				    failure: function(response, opts) {                    
				         Ext.callback(options.failure, options.scope, [rsp, opts]);
				    }
				});
	                return;
	         }
        }

        if (me.fireEvent('beforerequest', me, options) != false) {
            var rsp;
            try {
            	if(parms){
            		// format date to valid format
            		parms = Ext.JSON.decode(Ext.JSON.encode(parms));
            	}
            	
                var rpc = new RpcInvoker(me.broker, me.topic);
                var response = await rpc.invoke({
                    module: options.module,
                    params: parms
                });

                if (Ext.isString(response)) {
                    rsp = Ext.JSON.decode(response, true);
                } else if (Ext.isObject(response)) {
                    rsp = response;
                }

                me.fireEvent('requestcomplete', me, rsp, options);

                Ext.callback(options.callback, options.scope, [options, true, rsp]);
            } catch (ex) {
                Ext.Error.raise(ex.message);
                Ext.callback(options.callback, options.scope, [options, false, {
                    msg: ex.message
                }]);
            }

            if (rsp) {
                var success = (rsp.rspCode === "SYS-0000");
                Ext.require('Ext.MessageBox', function () {
                    if (options.showSuccess && success) {
                        Ext.Msg.show({
                            title: rsp.rspCode,
                            msg: rsp.rspDesc,
                            icon: Ext.Msg.INFO,
                            buttons: Ext.Msg.OK,
                            fn:function(){
                            	if(Ext.isFunction(options.msgFn)){
                            		 Ext.callback(options.msgFn, options.scope, [rsp, options]);
                            	}
                            }
                        });
                    }

                    if (options.showFail && !success) {
                        Ext.Msg.show({
                            title: rsp.rspCode,
                            msg: rsp.rspDesc,
                            icon: Ext.Msg.ERROR,
                            buttons: Ext.Msg.OK,
                            fn:function(){
                            	if(Ext.isFunction(options.msgFn)){
                            		 Ext.callback(options.msgFn, options.scope, [rsp, options]);
                            	}
                            }
                        });
                    }
                });

                Ext.callback(success ? options.success : options.failure, options.scope, [rsp, options]);
            }
        }
    },resolveFormRequest:function(formId){
    	var form = this.getForm({form:formId});
    	var files = Ext.query("input[type=file]",form);
    	if(Ext.isEmpty(files)){
    		return Ext.getCmp(formId).getValues();
    	}
    	
    	var reader = new FileReader();
    	var promise = new Promise(function(resolve,reject){	
	        reader.onload = function (e) {
			 if (!Ext.isEmpty(e.target.result)) {
			  var index = e.target.result.indexOf("base64,") + 7;
			  resolve(e.target.result.substr(index),true);
			  return;
			 };
	        	resolve(e,true);
	        };
	        reader.onerror = function(e){
	        	reject(e,false);
	        }
		});
	   // 将文件以Data URL形式读入页面
	   reader.readAsDataURL(files[0].files[0]);
		
	   var rtn={	   	
	   };
	   rtn[files[0].name]='',
	   rtn[files[0].name+"FileName"]=files[0].files[0].name;
	   
	   return promise.then(function(data){
	   	rtn[files[0].name]=data;
			return rtn;
		},function(data){
			return rtn;		
		});
	   
		/*
		return promise.then((data,success) => {
			if(success){
				rtn[files[0].name]=data;
				return rtn;
			}else{
				throw rtn;
			} 
        }).catch((e) => {});*/
    }
});
